﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PigArchives
{
    /// <summary>
    /// 品种handler
    /// </summary>
    public class SearchVarietiesHandler : IRequestHandler<SearchVarietiesCommand, Result>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 品种
        /// </summary>
        private readonly IBaseRepository<Varieties> varietiesrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchVarietiesHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="varietiesrepository"></param>
        /// <param name="logger"></param>
        public SearchVarietiesHandler(IMapper mapper, IBaseRepository<Varieties> varietiesrepository, ILogger<SearchVarietiesHandler> logger)
        {
            this.mapper = mapper;
            this.varietiesrepository = varietiesrepository;
            _logger = logger;
        }

        /// <summary>
        /// 品种显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SearchVarietiesCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var roles = await (await varietiesrepository.GetAll()).ToListAsync();
                result.Data = roles;
                result.Msg = "品种信息显示成功";
            }
            catch (Exception ex)
            {
                _logger.LogError("品种信息显示失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
